package com.kingyun.gpsinspection.purificationservice.services.jsm.outerservice.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.kingyun.gpsinspection.purificationservice.common.enums.WorkInstanceLevelEnum;
import com.kingyun.gpsinspection.purificationservice.dao.mapper.jsm.JsmEntityMapper;
import com.kingyun.gpsinspection.purificationservice.dao.mapper.jsm.JsmOrganizationMapper;
import com.kingyun.gpsinspection.purificationservice.dao.mapper.jsm.JsmWorkCellInstanceMapper;
import com.kingyun.gpsinspection.purificationservice.facade.model.jsm.*;
import com.kingyun.gpsinspection.purificationservice.facade.service.jsm.OutWorkCellInstanceService;
import com.kingyun.gpsinspection.purificationservice.facade.service.jsm.workcellinstance.JsmWorkCellInstanceService;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by zmling on 2017/1/12.
 */
public class OutWorkCellInstanceServiceImpl implements OutWorkCellInstanceService{
    @Autowired
    private JsmWorkCellInstanceService workCellInstanceService;

    @Autowired
    private JsmWorkCellInstanceMapper jsmWorkCellInstanceMapper;

    @Autowired
    private JsmOrganizationMapper orgMapper;

    @Autowired
    private JsmEntityMapper jsmEntityMapper;

    /**
     * 查询所有工作内容
     * @param workCellInstance
     * @return
     * @throws Exception
     */
    @Override
    public List<WorkCellInstance> findWorkCellInstance(WorkCellInstance workCellInstance) throws Exception {
        return workCellInstanceService.outFindWorkCellInstanceList(workCellInstance);
    }

    /**
     * 分页查询工作内容
     * @param workCellInstanceVo
     * @return
     * @throws Exception
     */
    @Override
    public JSONObject findWorkCellInstanceLimit(WorkCellInstanceVo workCellInstanceVo) throws Exception {
        return workCellInstanceService.table(workCellInstanceVo);
    }

    /**
     * @param workCellInstanceVo
     * @return JSONObject
     * @Author 卢曼成
     * @Description
     * @Date 2017/2/24 13:58
     */
    @Override
    public JSONObject queryInstanceInfoUnionList(WorkCellInstanceVo workCellInstanceVo) throws Exception {
        return workCellInstanceService.queryInstanceInfoUnionList(workCellInstanceVo);
    }

    /**
     *
     * @param employeeVo
     * @param workCellInstanceVo
     * @return JSONObject
     * @Author 卢曼成
     * @Description
     * @Date 2017/2/24 13:58
     */
    @Override
    public JSONObject queryInstanceInfoUnionList(EmployeeVo employeeVo, WorkCellInstanceVo workCellInstanceVo) throws Exception {
        JSONObject jsonObject = new JSONObject();

        workCellInstanceVo.setLimit(workCellInstanceVo.getLimit() == null ? 10 : workCellInstanceVo.getLimit());
        workCellInstanceVo.setOffset(workCellInstanceVo.getOffset() == null ? 0 : workCellInstanceVo.getOffset());
        if (StringUtils.isNotEmpty(workCellInstanceVo.getSearch())) {
            workCellInstanceVo.setSearch(workCellInstanceVo.getSearch().trim());
        }

        //需求更改：
        //原来需求：查询所有的操作单元和一站一案
        //新需求：场站只能看到本场站和作业区、气矿公共的一站一案，不能看到其他场站的一站一案；作业区人员只能看到本作业区和气矿公共的一站一案，不能看到其他作业区的一站一案；）
        String empOrgId = employeeVo.getOrgId();
        workCellInstanceVo.setFilterOrgId(empOrgId);
        jsonObject.put("total", jsmWorkCellInstanceMapper.queryInstanceInfoUnionCount(workCellInstanceVo));
        jsonObject.put("rows", JSON.toJSON(jsmWorkCellInstanceMapper.queryInstanceInfoUnionList(workCellInstanceVo)));
        return jsonObject;
    }


    /**
     * 根据ID查询一站一案和操作单元
     * @param workInstanceId
     * @return
     * @throws Exception
     */
    @Override
    public WorkCellInstanceVo queryInstanceInfoUnionById(String workInstanceId) throws Exception {
        return workCellInstanceService.queryInstanceInfoUnionById(workInstanceId);
    }

    /**
     * 查询一站一案和操作单元
     *
     * @param employeeVo
     * @param workCellInstanceVo
     * @param iconSkin
     * @return
     */
    @Override
    public JSONObject queryInstanceOrInfoUnion(EmployeeVo employeeVo, WorkCellInstanceVo workCellInstanceVo, String iconSkin) {
        JSONObject result=new JSONObject();
        String orgId = workCellInstanceVo.getOrgId();
        String workType = workCellInstanceVo.getWorkType();
        String entityId = workCellInstanceVo.getEntityId();
        String search = workCellInstanceVo.getSearch();
        if (!Strings.isNullOrEmpty(search)) {
            workCellInstanceVo.setSearch(search.trim());
        }

        //没有过滤条件：显示分公司的操作单元和本作业区的一站一案
        if(Strings.isNullOrEmpty(workType)){
            //需求更改：
            //原来需求：查询所有的操作单元和一站一案；
            //新需求：作业区不能看到其他作业区的一站一案，只能看到本作业区的一站一案和分公司的操作单元；
            //场站不能看到其他场站的一站一案，只能看到本场站的一站一案和父亲作业区的一站一案，及分公司的操作单元；
            String empOrgId = employeeVo.getOrgId();
            workCellInstanceVo.setEntityId(null);
            workCellInstanceVo.setDevTypeId(null);
            workCellInstanceVo.setFilterOrgId(empOrgId);
            result.put("total", jsmWorkCellInstanceMapper.queryInstanceInfoUnionCount(workCellInstanceVo));
            result.put("rows", JSON.toJSON(jsmWorkCellInstanceMapper.queryInstanceInfoUnionList(workCellInstanceVo)));
        //组织ID不为空
        }else if(!Strings.isNullOrEmpty(orgId)){
            if(!Strings.isNullOrEmpty(workType)){
                if(WorkInstanceLevelEnum.ORG_LEVEL_BRANCH.getCode().equals(workType)){//分公司
                //查询所有操作单元
                    workCellInstanceVo.setOrgId(null);
                    result.put("rows", jsmWorkCellInstanceMapper.queryCellInfoList(workCellInstanceVo));
                    result.put("total", jsmWorkCellInstanceMapper.queryCellInfoCount(workCellInstanceVo));
                }else if(WorkInstanceLevelEnum.ORG_LEVEL_DEVICE.getCode().equals(workType)){//设备
                //查询该组织下的所有设备的一站一案(包括子组织下的设备)
                    List<String> orgIds= Lists.newArrayList();
                    orgIds.add(orgId);
                    List<Organization> children= orgMapper.selectOrgByOrgPId(orgId);
                    if(children != null){
                        getChidrenOrgIds(children,orgIds);
                    }

                    List<String> entityIdList = new ArrayList<String>();
                    for(String s : orgIds){
                        List<EntityVo> list = jsmEntityMapper.selectByPOId(s);
                        if(list!=null){
                            for(EntityVo entityVO : list){
                                entityIdList.add(entityVO.getEnId());
                            }
                        }
                    }
                    workCellInstanceVo.setEntityIds(entityIdList);
                    result.put("rows",  jsmWorkCellInstanceMapper.queryInstanceListByEntityIds(workCellInstanceVo));
                    result.put("total", jsmWorkCellInstanceMapper.queryInstanceCountByEntityIds(workCellInstanceVo));
                }else{
                //其他组织
                    if(!Strings.isNullOrEmpty(iconSkin)){
                        String parentId = "";
                        String grandId = "";
                        String gasId = "";
                        String areaId = "";
                        String stationId = "";
                        String wellId = "";
                        String pipelineId = "";

                        if(iconSkin.equals("operating_area")){
                            areaId = orgId;
                            Organization organization = orgMapper.selectByPrimaryKey(orgId);
                            gasId = organization.getParentOrgId();
                        }

                        //执行对象判断：执行对象不能是分公司、气矿、作业区
                        if(iconSkin.equals("station")){
                            stationId = orgId;
                            Organization organization = orgMapper.selectByPrimaryKey(orgId);
                            areaId = organization.getParentOrgId();
                            organization = orgMapper.selectByPrimaryKey(areaId);
                            gasId = organization.getParentOrgId();

                        }
                        if(iconSkin.equals("well")){
                            wellId = orgId;
                            Organization organization = orgMapper.selectByPrimaryKey(orgId);
                            parentId = organization.getParentOrgId();
                            organization = orgMapper.selectByPrimaryKey(parentId);
                            if(organization.getOrgLevelId()!=null){
                                if(organization.getOrgLevelId().equals("3")){
                                    areaId = parentId;
                                    organization = orgMapper.selectByPrimaryKey(areaId);
                                    gasId = organization.getParentOrgId();
                                }else if(organization.getOrgLevelId().equals("4")){
                                    stationId = parentId;
                                    organization = orgMapper.selectByPrimaryKey(stationId);
                                    areaId = organization.getParentOrgId();
                                    organization = orgMapper.selectByPrimaryKey(areaId);
                                    gasId = organization.getParentOrgId();
                                }
                            }
                        }
                        if(iconSkin.equals("pipeline")){
                            Organization organization = orgMapper.selectByPrimaryKey(orgId);
                            pipelineId = orgId;
                            parentId = organization.getParentOrgId();
                            organization = orgMapper.selectByPrimaryKey(parentId);
                            if(organization.getOrgLevelId()!=null){
                                if(organization.getOrgLevelId().equals("3")){ //"3"作业区
                                    areaId = parentId;
                                    organization = orgMapper.selectByPrimaryKey(areaId);
                                    gasId = organization.getParentOrgId();
                                }else if(organization.getOrgLevelId().equals("4")){ //"4"场站
                                    stationId = parentId;
                                    organization = orgMapper.selectByPrimaryKey(stationId);
                                    areaId = organization.getParentOrgId();
                                    organization = orgMapper.selectByPrimaryKey(areaId);
                                    gasId = organization.getParentOrgId();
                                }else if(organization.getOrgLevelId().equals("5")){ //"5"井站
                                    wellId = parentId;
                                    organization = orgMapper.selectByPrimaryKey(wellId);
                                    grandId = organization.getParentOrgId();
                                    organization = orgMapper.selectByPrimaryKey(grandId);
                                    if(organization.getOrgLevelId()!=null){
                                        if(organization.getOrgLevelId().equals("3")){//"3"作业区
                                            areaId = grandId;
                                            organization = orgMapper.selectByPrimaryKey(areaId);
                                            gasId = organization.getParentOrgId();
                                        }else if(organization.getOrgLevelId().equals("4")){//"4"场站
                                            stationId = grandId;
                                            organization = orgMapper.selectByPrimaryKey(stationId);
                                            areaId = organization.getParentOrgId();
                                            organization = orgMapper.selectByPrimaryKey(areaId);
                                            gasId = organization.getParentOrgId();
                                        }
                                    }
                                }
                            }
                        }

                        //过滤条件判断
                        if(workType.equals(WorkInstanceLevelEnum.ORG_LEVEL_GAS_FIELD.getCode())){
                            workCellInstanceVo.setOrgId(gasId);
                        }else if(workType.equals(WorkInstanceLevelEnum.ORG_LEVEL_WORK_SPACE.getCode())){
                            workCellInstanceVo.setOrgId(areaId);
                        }else if(workType.equals(WorkInstanceLevelEnum.ORG_LEVEL_STATION.getCode())){
                            //执行对象选择作业区，筛选条件选择场站：只能看到当前人所属组织下的所有场站的一站一案
                            if(StringUtils.isBlank(stationId)){
                                String empOrgId = employeeVo.getOrgId();
                                workCellInstanceVo.setFilterOrgId(empOrgId);
                                //关键：必须设为空，否则查询单个entity_id=orgId
                                workCellInstanceVo.setOrgId(null);
                            }else{
                                workCellInstanceVo.setOrgId(stationId);
                            }

                        }

                        //查询当前组织下的一站一案
                        workCellInstanceVo.setEntityId(null);
                        workCellInstanceVo.setDevTypeId(null);
                        result.put("rows",  jsmWorkCellInstanceMapper.queryCellInstanceList(workCellInstanceVo));
                        result.put("total", jsmWorkCellInstanceMapper.queryCellInstanceCount(workCellInstanceVo));
                    }

                }
            }
        }else {
        //组织ID为空实体ID不为空
            if(!Strings.isNullOrEmpty(entityId)){
                if(!Strings.isNullOrEmpty(workType)){
                    if(WorkInstanceLevelEnum.ORG_LEVEL_BRANCH.getCode().equals(workType)){//分公司
                    //查询实体对应的操作单元
                        Entity entity = jsmEntityMapper.selectByEnId(entityId);
                        //设置生产实体类型ID
                        workCellInstanceVo.setDevTypeId(entity.getEnTypeId());
                        workCellInstanceVo.setEntityId(null);
                        workCellInstanceVo.setOrgId(null);
                        result.put("rows", jsmWorkCellInstanceMapper.queryCellInfoList(workCellInstanceVo));
                        result.put("total", jsmWorkCellInstanceMapper.queryCellInfoCount(workCellInstanceVo));
                    }else if(WorkInstanceLevelEnum.ORG_LEVEL_DEVICE.getCode().equals(workType)){//设备
                    //查询设备对应的一站一案
                        result.put("rows", jsmWorkCellInstanceMapper.queryInstanceByEntity(workCellInstanceVo));
                        result.put("total", jsmWorkCellInstanceMapper.queryInstanceByEntityCount(workCellInstanceVo));
                    }else{
                    //其他组织
                    //查询实体对应的一站一案
                        Entity entity = jsmEntityMapper.selectByEnId(entityId);
                        //设置生产实体类型ID
                        workCellInstanceVo.setDevTypeId(entity.getEnTypeId());
                        workCellInstanceVo.setEntityId(null);
                        workCellInstanceVo.setOrgId(null);
                        result.put("rows",  jsmWorkCellInstanceMapper.queryCellInstanceList(workCellInstanceVo));
                        result.put("total", jsmWorkCellInstanceMapper.queryCellInstanceCount(workCellInstanceVo));
                    }
                }
            }
        }
        return result;
    }


    /**
     * 得到所有的子孩子(组织)
     * @param children
     * @param retList
     */
    private void getChidrenOrgIds(List<Organization> children,List<String> retList){
        for(Organization organization:children){
            List<Organization> chil= orgMapper.selectOrgByOrgPId(organization.getOrgId());
            if(chil==null||chil.size()<=0){
                retList.add(organization.getOrgId());
            }else{
                getChidrenOrgIds(chil,retList);
            }
        }
    }

}
